package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.mapper.UserMapper;
import com.bwie.pojo.User;
import com.bwie.service.UserService;
import com.bwie.util.R;
import com.bwie.vo.UserVo;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.ChineseCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @program: day0513-week3
 * @ClassName UserServiceImpl
 * @description:
 * @author: 段阳
 * @create: 2024-05-13 09:37
 **/
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
    * //TODO //登录业务
    * @author 段阳
    * @date 2024/5/13 9:41
     * @param userVo
     * @return com.bwie.util.R
    */
    @Override
    public R login(UserVo userVo) {
        //判断账户内容
        if (StringUtils.isBlank(userVo.getUsername())){
            return R.error(500,"用户名不能为空!");
        }
        if (StringUtils.isBlank(userVo.getPassword())){
            return R.error(500,"密码不能为空!");
        }
        if (StringUtils.isBlank(userVo.getValidCode())){
            return R.error(500,"验证码不能为空!");
        }
        String codeKey = "CODE-"+userVo.getMobile();
        String code = stringRedisTemplate.opsForValue().get(codeKey);
        if (StringUtils.isBlank(code)){
            return R.error(500,"验证码已过期!");
        }
        if (!code.equals(userVo.getValidCode())){
            return R.error(500,"验证码错误!");
        }
        //查询账户
        User user1 = userMapper.selectOne(
                new QueryWrapper<User>()
                        .lambda()
                        .eq(User::getUsername, userVo.getUsername()));
        if (null == user1){
            return R.error(500,"用户名或密码错误！");
        }
        if (!userVo.getPassword().equals(user1.getPassword())){
            return R.error(500,"用户名或密码错误！");
        }


        //生成token令牌
        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, "bwie")
                .setIssuedAt(new Date())
                .claim("id", user1.getId())
                .compact();
        HashMap<String, Object> map = new HashMap<>();
        String tokenKey = "USER-TOKEN-"+user1.getId();
        stringRedisTemplate.opsForValue().set(tokenKey,token,30,TimeUnit.MINUTES);
        map.put("token",token);
        map.put("userRole",user1.getUserRole());
        //返回登录结果
        return R.success("登录成功",map);
    }

    @Override
    public R vCode(UserVo userVo) throws IOException {
//        if (StringUtils.isBlank(userVo.getMobile())){
//            return R.error(500,"手机号不能为空");
//        }
        ArithmeticCaptcha arithmeticCaptcha = new ArithmeticCaptcha(100,60,3);

        String text = arithmeticCaptcha.text();
        stringRedisTemplate.opsForValue().set("CODE-"+userVo.getMobile(),text,5, TimeUnit.MINUTES);
        return R.success("",arithmeticCaptcha.toBase64());


//        //生成图形验证码
//        SpecCaptcha specCaptcha = new SpecCaptcha(100, 60,6);
//        //获取值
//        String text = specCaptcha.text();
//        //存入缓存
//        stringRedisTemplate.opsForValue().set("CODE-"+userVo.getMobile(),text,5, TimeUnit.MINUTES);
//        //返回路径
//        return R.success("", specCaptcha.toBase64());
    }
}